<?php

namespace app\modules\weixin\controllers;

use app\common\services\ShortMessageServices;
use app\common\services\StaticServices;
use app\models\Member;
use app\models\Recommend;
use app\models\User;
use app\modules\weixin\controllers\common\BaseController;
use Yii;
use yii\base\Exception;
use yii\web\Response;

class CommonController extends BaseController
{
    public function actionLogin()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $phone = trim(Yii::$app->request->post('user_phone', ''));
            $user_pwd = trim(Yii::$app->request->post('user_pwd', ''));
            if (mb_strlen($phone, 'utf-8') != 11 && !preg_match("/^1[34578]{1}\d{9}$/", $phone)) {
                throw new Exception('请填写正确的电话号码');
            }
            if (!Member::checkPwd($user_pwd, $phone)) {
                throw new Exception('密码或者用户名有误');
            }

            $member_info = Member::find()->where(['member_phone' => $phone, 'member_status' => 1, 'self_status' => 1])->one();
            if ($member_info) {
                $member_info->update_time = time();
                $member_info->save(0);
                Yii::$app->session->set('member_info', $member_info);
                return ['code' => 200, 'member_id' => $member_info->id];
            } else {
                throw new Exception('没有此用户');
            }
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionLogout()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        Yii::$app->session->remove('member_info');
        return ['code' => 200, 'msg' => '退出成功'];
    }

    public function actionModifyPwd()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $member_id = intval(Yii::$app->request->post('member_id'));
            $new_pwd = trim(Yii::$app->request->post('new_pwd'));
            $confirm_pwd = trim(Yii::$app->request->post('confirm_pwd'));
            if (mb_strlen($new_pwd, 'utf-8') < 6 || mb_strlen($confirm_pwd, 'utf-8') < 6 || $new_pwd != $confirm_pwd) {
                throw new Exception('填写密码有误');
            }
            $code = Yii::$app->request->post('code');
            $short_msg = new ShortMessageServices();
            $check_code = $short_msg->CheckCode($code);
            if ($check_code['code'] == 200) {
                $member_info = Member::find()->where(['id' => $member_id, 'self_status' => 1])->one();
                $member_info->member_pwd = md5($new_pwd);
                $member_info->save(0);
                $short_msg->UseCode($code);
                return ['code' => 200, 'msg' => '更新成功'];
            } else {
                throw new Exception($check_code['msg']);
            }
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionForgetPwd()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $member_phone = trim(Yii::$app->request->post('member_phone'));
            $new_pwd = trim(Yii::$app->request->post('new_pwd'));
            $code = trim(Yii::$app->request->post('code'));

            if (!preg_match("/^1[34578]{1}\d{9}$/", $member_phone)) {
                throw new Exception('请填写正确的手机号码');
            }
            if (mb_strlen($new_pwd, 'utf-8') < 6) {
                throw new Exception('密码不能小于6位');
            }
            $member_info = Member::find()->where(['member_phone' => $member_phone])->one();
            if (!$member_info) {
                throw new Exception('无此用户');
            }
            $short_msg = new ShortMessageServices();
            $check_code = $short_msg->CheckCode($code);
            if ($check_code['code'] == 200) {
                $member_info->member_pwd = md5($new_pwd);
                $member_info->update_time = time();
                $member_info->save(0);
                $short_msg->UseCode($code);
                return ['code' => 200, 'msg' => '修改成功'];
            } else {
                throw new Exception($check_code['msg']);
            }
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionGetModifyCode()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $phone = trim(Yii::$app->request->post('phone'));
            $type = trim(Yii::$app->request->post('type'));

            if (!preg_match('/^(0|86|17951)?(1[356789])[0-9]{9}$/', $phone)) {
                throw new Exception('请输入正确的电话号码');
            }
            if ($type == 'member') {
                $member_info = Member::find()->where(['member_phone' => $phone])->one();
                if (!$member_info || $member_info->self_status == 0) {
                    throw new Exception('此用户不存在');
                }
            }
            if ($type == 'user') {
                $user_info = User::find()->where(['user_phone' => $phone])->one();

                if (!$user_info || $user_info->user_status == 0) {
                    throw new Exception('用户已经不存在');
                }
            }

            $template = '您正在进行修改密码操作，验证码为{code}，5分钟内有效；如非本人操作，请忽略此短信。';
            if ($member_info) {
                StaticServices::getCode(mt_rand(100000, 999999), $template, $member_info->member_phone, 3);
                return ['code' => 200, 'msg' => '发送成功'];
            } elseif ($user_info) {
                StaticServices::getCode(mt_rand(100000, 999999), $template, $user_info->user_phone, 3);
                return ['code' => 200, 'msg' => '发送成功'];
            } else {
                throw new Exception('参数有误');
            }
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionUserModifyPwd()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $user_pwd = trim(Yii::$app->request->post('user_pwd'));
            $confirm_pwd = trim(Yii::$app->request->post('confirm_pwd'));
            $code = trim(Yii::$app->request->post('code'));

            if (mb_strlen($user_pwd, 'utf-8') < 6 || mb_strlen($confirm_pwd, 'utf-8') < 6) {
                throw new Exception('请正确输入密码');
            }
            $short_msg = new ShortMessageServices();
            $check_code = $short_msg->CheckCode($code);
            if ($check_code['code'] != 200) {
                throw new Exception($check_code['msg']);
            }
            $session_user = Yii::$app->session->get('user_info');
            $user_info = User::find()->where(['id' => $session_user['id']])->one();
            $user_info->user_pwd = md5($user_pwd);
            $user_info->update_time = time();
            $user_info->save(0);
            $short_msg->UseCode($code);
            return ['code' => 200, 'msg' => '修改成功'];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionUserValidateCode()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $user_phone = trim(Yii::$app->request->post('user_phone'));
            $template = '亲爱的经纪人，您的注册验证码为{code}，5分钟内有效；如非本人操作，请忽略此短信。';
            StaticServices::getCode(mt_rand(100000, 999999), $template, $user_phone, 2);
            return ['code' => 200, 'msg' => '发送成功'];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionUserLogin()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $user_phone = trim(Yii::$app->request->post('user_phone'));
            $user_pwd = trim(Yii::$app->request->post('user_pwd'));
            if (mb_strlen($user_phone, 'utf-8') != 11 && !preg_match("/^1[34578]{1}\d{9}$/", $user_phone)) {
                throw new Exception('请填写正确的电话号码');
            }
            if (!User::checkPwd($user_pwd, $user_phone)) {
                throw new Exception('用户名和密码有误');
            }
            $user_info = User::find()->where(['user_phone' => $user_phone, 'user_status' => 1])->one();
            //判断经纪人推荐用户是否过期
            $recommend_info = Recommend::find()->where(['recommend_type' => 9])->asArray()->all();
            foreach ($recommend_info as $item) {
                if (time() - $item['update_time'] > 60 * 60 * 24 * 30) {
                    $recommend = Recommend::find()->where(['id' => $item['id']])->one();
                    $recommend->recommend_type = 7;
                    $recommend->update_time = time();
                    $recommend->save(0);
                }
            }
            if (!$user_info) {
                throw new Exception('数据有误');
            } else {
                $user_info->update_time = time();
                $user_info->save(0);
                Yii::$app->session->set('user_info', $user_info);
                return ['code' => 200, 'user_id' => $user_info->id, 'user_role' => $user_info->user_role];
            }
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionUserLogout()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        Yii::$app->session->remove('user_info');
        return ['code' => 200, 'msg' => '退出登录'];
    }

    public function actionUserRegister()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $user_name = trim(Yii::$app->request->post('user_name'));
            $user_ID = trim(Yii::$app->request->post('user_ID'));
            $user_phone = trim(Yii::$app->request->post('user_phone'));
            $user_pwd = trim(Yii::$app->request->post('user_pwd'));
            $confirm_pwd = trim(Yii::$app->request->post('confirm_pwd'));
            $validate_code = trim(Yii::$app->request->post('validate_code'));
            $short_msg = new ShortMessageServices();
            $check_code = $short_msg->CheckCode($validate_code);

            if (mb_strlen($user_name, 'utf-8') < 1) {
                throw new Exception('请填写用户名');
            }
            if (!StaticServices::is_idcard($user_ID)) {
                throw new Exception('请填写正确的身份证号');
            }
            if (mb_strlen($user_phone, 'utf-8') != 11 && !preg_match("/^1[34578]{1}\d{9}$/", $user_phone)) {
                throw new Exception('请填写正确的电话号码');
            }

            if (mb_strlen($user_pwd, 'utf-8') < 6 || mb_strlen($confirm_pwd, 'utf-8') < 6) {
                throw new Exception('密码需要6位');
            }

            if ($user_pwd != $confirm_pwd) {
                throw new Exception('两次密码不一致');
            }
            $user_info = User::find()->where(['user_phone' => $user_phone])->one();
            if ($user_info) {
                throw new Exception('用户已经存在');
            }

            $user_arr = User::find()->where(['user_ID' => $user_ID])->one();
            if ($user_arr) {
                throw new Exception('此身份证已经使用过');
            }

            if ($check_code['code'] != 200) {
                throw new Exception($check_code['msg']);
            }

            $user = new User();
            $user->user_name = $user_name;
            $user->user_phone = $user_phone;
            $user->user_pwd = md5($user_pwd);
            $user->user_ID = $user_ID;
            $user->update_time = time();
            $user->create_time = time();
            $user->save(0);
            $short_msg->UseCode($validate_code);
            return ['code' => 200, 'msg' => '注册成功'];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionUserForgetPwd()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $user_name = trim(Yii::$app->request->post('user_name'));
            $user_phone = trim(Yii::$app->request->post('user_phone'));
            $user_pwd = trim(Yii::$app->request->post('user_pwd'));
            $confirm_pwd = trim(Yii::$app->request->post('confirm_pwd'));
            $code = trim(Yii::$app->request->post('code'));

            if (mb_strlen($user_name, 'utf-8') < 1) {
                throw new Exception('请填写用户姓名');
            }

            if (!preg_match("/^1[34578]{1}\d{9}$/", $user_phone)) {
                throw new Exception('请填写正确的电话号码');
            }
            if (mb_strlen($user_pwd, 'utf-8') < 6 || mb_strlen($confirm_pwd, 'utf-8') < 6 || $user_pwd != $confirm_pwd) {
                throw new Exception('请正确输入密码');
            }
            $short_msg = new ShortMessageServices();
            $check_code = $short_msg->CheckCode($code);
            if ($check_code['code'] != 200) {
                throw new Exception($check_code['msg']);
            }
            $user_info = User::find()->where(['user_name' => $user_name, 'user_phone' => $user_phone])->one();
            if (!$user_info) {
                throw new Exception('此用户不存在');
            }
            $user_info->user_pwd = md5($user_pwd);
            $user_info->update_time = time();
            $user_info->save(0);
            $short_msg->UseCode($code);
            return ['code' => 200, 'msg' => '修改成功'];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionTest()
    {
        $recommend_info = Recommend::find()->where(['recommend_type' => 9])->asArray()->all();
        foreach ($recommend_info as $item) {
            if (time() - $item['update_time'] > 60 * 60) {
                $recommend = Recommend::find()->where(['id' => $item['id']])->one();
                $recommend->recommend_type = 7;
                $recommend->update_time = time();
                $recommend->save(0);
            }
        }
        echo 123;
    }
}